<template>
  <div class="ero-table-container">
    <!-- 搜索区域 -->
    <div class="gva-search-box">
      <el-form
          ref="elSearchFormRef"
          :inline="true"
          :model="searchInfo"
          class="demo-form-inline"
          @keyup.enter="onSubmit"
      >
        <!-- 筛选框1 -->
        <el-form-item label="型号">
          <el-select
              v-model="searchInfo.filter1"
              placeholder="请选择"
              clearable
              @change="handleFilterChange"
          >
            <el-option
                v-for="item in filterOption1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 筛选框2（模拟级联，可根据筛选1动态加载） -->
        <el-form-item label="编号">
          <el-select
              v-model="searchInfo.filter2"
              placeholder="请选择"
              clearable
          >
            <el-option
                v-for="item in filterOption2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 日期范围筛选 -->
        <el-form-item label="创建日期" prop="createdAtRange">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker
              v-model="searchInfo.createdAtRange"
              class="w-[380px]"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </el-form-item>

        <!-- 查询/重置/展开按钮 -->
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button
              link
              type="primary"
              icon="arrow-down"
              @click="showAllQuery = true"
              v-if="!showAllQuery"
          >
            展开
          </el-button>
          <el-button
              link
              type="primary"
              icon="arrow-up"
              @click="showAllQuery = false"
              v-else
          >
            收起
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="gva-table-box">
      <!-- 操作按钮 -->
      <div class="gva-btn-list">
        <el-button v-auth="btnAuth.add" type="primary" icon="plus" @click="openDialog()">
          新增
        </el-button>
        <el-button
            v-auth="btnAuth.batchDelete"
            icon="delete"
            style="margin-left: 10px;"
            :disabled="!multipleSelection.length"
            @click="onDelete"
        >
          删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
          ref="multipleTable"
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableData"
          row-key="ID"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column sortable align="left" label="日期" prop="CreatedAt" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="型号" prop="eroPartModel" width="120" />
        <el-table-column align="left" label="编号" prop="eroPartID" width="120" />
        <el-table-column align="left" label="次数" prop="useTimes" width="120" />
        <el-table-column align="left" label="天数" prop="operationDays" width="120" />
        <el-table-column align="left" label="日期" prop="operationDate" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.operationDate) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="同步日期" prop="syncDate" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.syncDate) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
          <template #default="scope">
            <el-button
                v-auth="btnAuth.info"
                type="primary"
                link
                class="table-button"
                @click="getDetails(scope.row)"
            >
              <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看
            </el-button>
            <el-button
                v-auth="btnAuth.edit"
                type="primary"
                link
                icon="edit"
                class="table-button"
                @click="updateErotableFunc(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                v-auth="btnAuth.delete"
                type="primary"
                link
                icon="delete"
                @click="deleteRow(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="gva-pagination">
        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-drawer
        destroy-on-close
        :size="appStore.drawerSize"
        v-model="dialogFormVisible"
        :show-close="false"
        :before-close="closeDialog"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ type === 'create' ? '新增' : '编辑' }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog">
              确 定
            </el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>
      <el-form
          :model="formData"
          label-position="top"
          ref="elFormRef"
          :rules="rule"
          label-width="80px"
      >
        <el-form-item label="型号:" prop="eroPartModel">
          <el-input
              v-model="formData.eroPartModel"
              :clearable="false"
              placeholder="请输入型号"
          />
        </el-form-item>
        <el-form-item label="编号:" prop="eroPartID">
          <el-input
              v-model="formData.eroPartID"
              :clearable="false"
              placeholder="请输入编号"
          />
        </el-form-item>
        <el-form-item label="次数:" prop="useTimes">
          <el-input
              v-model.number="formData.useTimes"
              :clearable="false"
              placeholder="请输入次数"
          />
        </el-form-item>
        <el-form-item label="天数:" prop="operationDays">
          <el-input
              v-model.number="formData.operationDays"
              :clearable="false"
              placeholder="请输入天数"
          />
        </el-form-item>
        <el-form-item label="日期:" prop="operationDate">
          <el-date-picker
              v-model="formData.operationDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              :clearable="false"
          />
        </el-form-item>
        <el-form-item label="同步日期:" prop="syncDate">
          <el-date-picker
              v-model="formData.syncDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              :clearable="false"
          />
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 详情弹窗 -->
    <el-drawer
        destroy-on-close
        :size="appStore.drawerSize"
        v-model="detailShow"
        :show-close="true"
        :before-close="closeDetailShow"
        title="查看"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="型号">
          {{ detailFrom.eroPartModel }}
        </el-descriptions-item>
        <el-descriptions-item label="编号">
          {{ detailFrom.eroPartID }}
        </el-descriptions-item>
        <el-descriptions-item label="次数">
          {{ detailFrom.useTimes }}
        </el-descriptions-item>
        <el-descriptions-item label="天数">
          {{ detailFrom.operationDays }}
        </el-descriptions-item>
        <el-descriptions-item label="日期">
          {{ detailFrom.operationDate }}
        </el-descriptions-item>
        <el-descriptions-item label="同步日期">
          {{ detailFrom.syncDate }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  createErotable,
  deleteErotable,
  deleteErotableByIds,
  updateErotable,
  findErotable,
  getErotableList,
} from '@/api/wearingparts/eroTable'; // 替换为实际接口路径
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  filterDataSource,
  returnArrImg,
  onDownloadFile,
} from '@/utils/format'; // 替换为实际工具路径
import { ElMessage, ElMessageBox, ElOption, ElSelect, ElDatePicker } from 'element-plus';
import { ref, reactive, onMounted, watch } from 'vue';
import { useBtnAuth } from '@/utils/btnAuth'; // 按钮权限工具
import { useAppStore } from '@/pinia'; // Pinia 存储
import { QuestionFilled, InfoFilled } from '@element-plus/icons-vue'; // 图标

defineOptions({
  name: 'Erotable',
});

// 按钮权限
const btnAuth = useBtnAuth();
const appStore = useAppStore();

// 响应式数据
const showAllQuery = ref(false);
const searchInfo = ref({
  filter1: 'SZ-GK01', // 筛选框1默认值
  filter2: 'SZ-GK01-00001', // 筛选框2默认值
  createdAtRange: [], // 日期范围
});

// 下拉选项（模拟，实际可接口获取）
const filterOption1 = ref([
  { label: 'SZ-GK01', value: 'SZ-GK01' },
  { label: 'SZ-KS01', value: 'SZ-KS01' },
]);
const filterOption2 = ref([
  { label: 'SZ-GK01-00001', value: 'SZ-GK01-00001' },
  { label: 'SZ-GK01-00002', value: 'SZ-GK01-00002' },
]);

// 表格数据
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);

// 弹窗 & 表单
const dialogFormVisible = ref(false);
const type = ref('create'); // create/update
const formData = ref({
  eroPartModel: '',
  eroPartID: '',
  useTimes: 0,
  operationDays: 0,
  operationDate: new Date(),
  syncDate: new Date(),
});
const rule = reactive({
  eroPartModel: [
    {
      required: true,
      message: '型号不能为空',
      trigger: ['input', 'blur'],
    },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur'],
    },
  ],
  eroPartID: [
    {
      required: true,
      message: '编号不能为空',
      trigger: ['input', 'blur'],
    },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur'],
    },
  ],
});
const btnLoading = ref(false);
const elFormRef = ref();
const elSearchFormRef = ref();

// 多选
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};
const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

// 筛选框变化（可扩展级联逻辑）
const handleFilterChange = () => {
  // 若需要筛选框2随筛选框1变化，可在此更新 filterOption2
  // 例如：filterOption2.value = 新的选项列表
};

// 查询
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    page.value = 1;
    getTableData();
  });
};

// 重置
const onReset = () => {
  searchInfo.value = {
    filter1: 'SZ-GK01',
    filter2: 'SZ-GK01-00001',
    createdAtRange: [],
  };
  getTableData();
};

// 获取表格数据
const getTableData = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value,
  };
  const res = await getErotableList(params);
  if (res.code === 0) {
    tableData.value = res.data.list;
    total.value = res.data.total;
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
  }
};

onMounted(() => {
  getTableData();
});

// 弹窗操作
const openDialog = () => {
  type.value = 'create';
  dialogFormVisible.value = true;
  formData.value = {
    eroPartModel: '',
    eroPartID: '',
    useTimes: 0,
    operationDays: 0,
    operationDate: new Date(),
    syncDate: new Date(),
  };
};

const closeDialog = () => {
  dialogFormVisible.value = false;
  elFormRef.value?.resetFields();
};

const enterDialog = async () => {
  btnLoading.value = true;
  elFormRef.value?.validate(async (valid) => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    let res;
    if (type.value === 'create') {
      res = await createErotable(formData.value);
    } else {
      res = await updateErotable(formData.value);
    }
    btnLoading.value = false;
    if (res.code === 0) {
      ElMessage.success('操作成功');
      closeDialog();
      getTableData();
    }
  });
};

// 编辑
const updateErotableFunc = async (row) => {
  const res = await findErotable({ ID: row.ID });
  if (res.code === 0) {
    type.value = 'update';
    formData.value = res.data;
    dialogFormVisible.value = true;
  }
};

// 删除
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await deleteErotable({ ID: row.ID });
    if (res.code === 0) {
      ElMessage.success('删除成功');
      getTableData();
    } else {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
</script>